package com.zidongxiangxi.rabbit.producer.sql;

import org.springframework.util.StringUtils;

/**
 * rabbitMQ顺序发送记录sql提供者
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class ProducerSequenceSqlProvider {
	private static final String DEFAULT_TABLE_NAME = "producer_sequence";
	private static final String INSERT_SQL = "insert into %s (id, application, group_name, message_id) values (?, ?, " +
			"?, ?)";
	private static final String SELECT_BY_ID_SQL = "select * from %s where id=?";
	private static final String SELECT_BY_MESSAGE_ID_SQL = "select * from %s where application=? and message_id=?";
	private static final String SELECT_PREVIOUS_ID_SQL = "select max(id) from %s where application=? and group_name=? "
			+ "and id < ?";
	private static final String LIST_SQL = "select * from %s where create_time < ? order by create_time "
			+ "limit ?";
	private static final String DELETE_SQL = "delete from %s where id in (:ids)";

	private final String insertSql, selectByIdSql, selectByMessageId, selectPreviousId, listSql, deleteSql;

	public ProducerSequenceSqlProvider() {
		this(DEFAULT_TABLE_NAME);
	}

	public ProducerSequenceSqlProvider(String tableName) {
		tableName = StringUtils.isEmpty(tableName) ? DEFAULT_TABLE_NAME : tableName;
		insertSql = String.format(INSERT_SQL, tableName);
		selectByIdSql = String.format(SELECT_BY_ID_SQL, tableName);
		selectByMessageId = String.format(SELECT_BY_MESSAGE_ID_SQL, tableName);
		selectPreviousId = String.format(SELECT_PREVIOUS_ID_SQL, tableName);
		listSql = String.format(LIST_SQL, tableName);
		deleteSql = String.format(DELETE_SQL, tableName);
	}


	public String getInsertSql() {
		return insertSql;
	}

	public String getSelectByIdSql() {
		return selectByIdSql;
	}

	public String getSelectByMessageIdSql() {
		return selectByMessageId;
	}

	public String getSelectPreviousIdSql() {
		return selectPreviousId;
	}

	public String getListSql() {
		return listSql;
	}

	public String getDeleteSql() {
		return deleteSql;
	}
}
